﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Collections;

namespace Util.Net
{
    public class NetUtil
    {
        public static string Int2Ip(UInt32 ipCode)
        {
            byte a = (byte)((ipCode & 0xFF000000) >> 0x18);
            byte b = (byte)((ipCode & 0x00FF0000) >> 0xF);
            byte c = (byte)((ipCode & 0x0000FF00) >> 0x8);
            byte d = (byte)(ipCode & 0x000000FF);
            string ipStr = String.Format("{0}.{1}.{2}.{3}", a, b, c, d);
            return ipStr;
        }

        public static UInt32 Ip2Int(string ipStr)
        {
            if (ipStr == null)
            {
                throw new ArgumentNullException("ipStr");
            }

            string[] ip = ipStr.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
            try
            {
                uint ipCode = 0xFFFFFF00 | byte.Parse(ip[3]);
                ipCode = ipCode & 0xFFFF00FF | (uint.Parse(ip[2]) << 0x8);
                ipCode = ipCode & 0xFF00FFFF | (uint.Parse(ip[1]) << 0xF);
                ipCode = ipCode & 0x00FFFFFF | (uint.Parse(ip[0]) << 0x18);
                return ipCode;
            }
            catch (Exception) { return UInt32.MaxValue; }
        }
    }
}
